import sqlalchemy

from app.datatype.session_msg import (
    SessionMsgDetailMdl, SessionMsg, SessionMsgListMdl, SessionMsgCreateMdl, SessionMsgUpdateMdl, SessionMsgDeleteMdl,
    SessionMsgListGetMdl,
)
from app.initializer import g
from app.utils import db_async


class SessionMsgDetailBiz(SessionMsgDetailMdl):

    async def detail(self):
        # TODO: 业务逻辑
        pass

# 获取聊天记录
class SessionMsgListBiz(SessionMsgListGetMdl):

    async def lst(self):
        #查询 sessionList 通过userid order by created_at desc 并且非删除状态
        sql = sqlalchemy.text(f"SELECT id,session_id,content,content_relevancy FROM {SessionMsg.__tablename__} "
               f"WHERE session_id = :session_id AND is_deleted = 0 "
               f"ORDER BY created_at asc ")
        async with g.db_async_session() as session:
            result = await session.execute(sql,{"session_id": self.session_id})
            rows = result.fetchall()
            field_names = list(SessionMsgListMdl.__fields__.keys())
            # 如果没有数据，返回空列表
            print("!!!!!!!rows:", rows)
            if rows is None or not rows or len(rows) == 0:
                return []

            return [SessionMsgListMdl(**dict(zip(field_names, row))).dict() for row in rows]
class MsgDetailBiz(SessionMsgListMdl):

    async def detail(self):
        async with g.db_async_session() as session:
            data = await db_async.query_one(
                session=session,
                model=SessionMsg,
                fields=self.response_fields(),
                filter_by={"id": self.id},
            )
            return data
# 创建聊天记录
class SessionMsgCreateBiz(SessionMsgCreateMdl):
    async def create(self):
        async with g.db_async_session() as session:
            return await db_async.create(
                session=session,
                model=SessionMsg,
                data={
                    "session_id": self.session_id,
                    "content": self.content,
                    "content_relevancy": self.content_relevancy,
                }
            )

# Update聊天记录
class SessionMsgUpdateBiz(SessionMsgUpdateMdl):
    async def update(self):
        async with g.db_async_session() as session:
            return await db_async.update(
                session=session,
                model=SessionMsg,
                data={
                    "content": self.content,
                },
                filter_by={"id": self.id},
            )
#删除聊天记录
class SessionMsgDeleteBiz(SessionMsgDeleteMdl):

    async def delete(self):
        async with g.db_async_session() as session:
            return await db_async.update(
                session=session,
                model=SessionMsg,
                data={
                    "is_deleted": 1,
                },
                filter_by={"id": self.id}
            )